<template>
  <view class="lecturer-wrap" :data-theme="globPrimary">
    <u-navbar
      :border-bottom="false"
      :back-icon-color="navbarStyle.iconColor"
      :immersive="true"
      :background="navbarStyle.backgroundColor"
      :custom-back="onBack"
    >
      <view slot="right" class="share-btn">
        <!-- #ifdef MP -->
        <button open-type="share" class="u-reset-button u-fix-ios-appearance">
          <u-icon name="zhuanfa" color="#ffffff" size="33"></u-icon>
        </button>
        <!-- #endif -->
        <!-- #ifdef APP-PLUS -->
        <u-icon name="zhuanfa" color="#ffffff" size="33" @click="onShare"></u-icon>
        <!-- #endif -->
      </view>
    </u-navbar>
    <view class="lecturer-header-fixed">
      <view class="lecturer-header">
        <view :style="[lecturerHeaderHeightStyle]"></view>
        <view class="lecturer-header__content u-flex">
          <view class="avatar u-flex">
            <u-avatar :src="userBasicData.avatar_url" size="140"></u-avatar>
          </view>
          <template v-if="!loading">
            <view class="content">
              <view v-if="isTeacher" class="u-flex">
                <view class="title u-line-1">{{ userBasicData.title }}</view>
                <u-image
                  width="57"
                  height="32"
                  :src="userBasicData.icon_url"
                  v-if="userBasicData.icon_url"
                ></u-image>
              </view>
              <view v-else class="title u-line-1">{{ userBasicData.nick_name }}</view>

              <template v-if="isTeacher">
                <view v-if="userBasicData.mhm_id != 1" class="desc" @click="toScholl">
                  <view class="u-line-1">{{ userBasicData.school_name }}</view>
                  <u-icon name="arrow-right" color="#fff" size="18"></u-icon>
                </view>
              </template>
              <template v-else>
                <view v-if="userBasicData.signature" class="desc">
                  <view class="u-line-1">{{ userBasicData.signature }}</view>
                </view>
              </template>
            </view>

            <view class="question-btn u-flex" v-if="!isTeacher && isUser" @click="toUserEdit">
              <u-icon name="edit-pen" color="#fff" size="18"></u-icon>
              <text>编辑资料</text>
            </view>
            <template v-if="isTeacher || !isUser">
              <view class="follow-btn u-flex" @click="handleFollowChange">
                <u-icon
                  :name="
                    userBasicData.is_follow == 1 || userBasicData.followed == 1
                      ? 'checkmark'
                      : 'plus'
                  "
                  :color="globPrimaryColor"
                  size="18"
                ></u-icon>
                <text>{{
                  userBasicData.is_follow == 1 || userBasicData.followed == 1 ? '已关注' : '关注'
                }}</text>
              </view>
              <view class="question-btn u-flex" @click="openQuestion">
                <u-icon name="edit-pen" color="#fff" size="18"></u-icon>
                <text>提问</text>
              </view>
            </template>
          </template>
        </view>
        <view class="lecturer-header__visitor u-flex">
          <template v-if="!loading">
            <view @click="toVisitor('pageFound/user/follow')">
              <view class="num">{{
                userBasicData.follow || userBasicData.following_num || 0
              }}</view>
              <view class="text">关注</view>
            </view>
            <view @click="toVisitor('pageFound/user/fans')">
              <view class="num">{{ userBasicData.follower || userBasicData.fans_num || 0 }}</view>
              <view class="text">粉丝</view>
            </view>
            <view @click="toVisitor('pageFound/user/visitor')">
              <view class="num">{{
                userBasicData.recent_visitors || userBasicData.recent_visitor_num || 0
              }}</view>
              <view class="text">最近访客</view>
            </view>
          </template>
        </view>
      </view>
      <!-- sticky吸顶悬浮的菜单, 父元素必须是 mescroll -->
      <view class="lecturer-tabs u-border-bottom">
        <u-tabs-swiper
          v-if="!loading"
          :activeColor="globPrimaryColor"
          ref="tabs"
          :list="tabList"
          :current="tabCurrentIndex"
          @change="tabChange"
          :is-scroll="false"
          :bar-style="{ bottom: '0px' }"
        ></u-tabs-swiper>
      </view>
    </view>

    <mescroll-body
      :top="mescrollTop"
      :down="{ auto: false }"
      ref="mescrollRef"
      @init="mescrollInit"
      @down="downCallback"
      @up="upCallback"
    >
      <view class="lecturer-main">
        <template v-if="!loading">
          <view v-if="tabCurrentType == 0" class="lecturer-introduce">
            <u-parse :html="userBasicData.info_text"></u-parse>
          </view>

          <!-- 动态模块 -->
          <dymic
            v-else-if="tabCurrentType == 1"
            showGroup
            :dymiclist="tabList[tabCurrentIndex].goods"
            @thumbUp="handleDynamicLike"
            @toDetail="handleDynamicReply"
            @zhuanfa="handleDynamicForward"
          ></dymic>

          <!-- 课程模块 -->
          <template v-else-if="tabCurrentType == 2">
            <view class="lecturer-course-tab u-flex">
              <view
                class="item"
                :class="[{ active: courseType == item.type }]"
                @click="courseTabChange(item.type)"
                v-for="(item, index) in courseTabList"
                :key="index"
                >{{ item.name }}</view
              >
            </view>
            <u-row class="rowlist" gutter="18">
              <u-col span="6" v-for="(item, index) in tabList[tabCurrentIndex].goods" :key="index">
                <course-row :data="item" @path="handleCoursePath(item.id)"></course-row>
              </u-col>
            </u-row>
          </template>
        </template>
      </view>
    </mescroll-body>

    <!-- 提问弹窗 -->
    <u-popup v-model="questionShow" mode="bottom">
      <view class="question-wrap" :style="{ 'padding-bottom': keyboardheight + 10 + 'px' }">
        <view class="u-flex">
          <edu-upload
            ref="uUpload"
            :value.sync="attachList"
            :args="{
              width: '100rpx',
              header: '100rpx',
              count: 9,
              customBtn: true,
              showUploadList: false,
            }"
            @on-list-change="onListChange"
          >
            <view slot="addBtn">
              <u-image width="40rpx" height="40rpx" src="@/pageFound/static/images/img_icon.png">
              </u-image>
            </view>
          </edu-upload>
          <view class="left">
            <textarea
              class="textarea"
              :value="questionContent"
              placeholder-class="placeholder"
              placeholder="请输入问题内容～"
              :show-confirm-bar="false"
              :adjust-position="false"
              :maxlength="200"
              :auto-height="true"
              @focus="questionFocus"
              @blur="questionBlur"
              @input="questionInput"
            />
          </view>
          <edu-button
            type="primary"
            size="medium"
            shape="circle"
            :disabled="contentDisabled"
            @click="submitQuestion"
            >发送</edu-button
          >
        </view>
        <view class="pre-box">
          <view class="pre-item" v-for="(item, index) in attachImg" :key="index">
            <image class="pre-item-image" :src="item.url" mode="aspectFill"></image>
            <view class="u-delete-icon" @tap.stop="deleteItem(index)">
              <u-icon name="close" size="12" color="#ffffff"></u-icon>
            </view>
          </view>
        </view>
      </view>
    </u-popup>

    <edu-user-coupon></edu-user-coupon>
  </view>
</template>

<script>
import dymic from '../circle/components/dymic.vue'
import courseRow from '@/components/common/courseRow.vue'
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js'
import { mapGetters } from 'vuex'
import setting from '@/settings/projectSetting.js'
// #ifdef APP-PLUS
import UniShare from 'uni_modules/uni-share/js_sdk/uni-share.js'
const uniShare = new UniShare()
// #endif
// #ifdef H5
import { wxShare } from '@/utils/share.js'
// #endif
export default {
  mixins: [MescrollMixin],
  components: {
    dymic,
    courseRow,
  },
  data() {
    return {
      setting,
      navbarStyle: {
        iconColor: '#ffffff',
        backgroundColor: {
          backgroundColor: 'transparent',
        },
      },
      tabList: [
        { name: '动态', type: 1, goods: [], num: 1, y: 0, curPageLen: 0, hasNext: true },
        { name: '课程', type: 2, goods: [], num: 1, y: 0, curPageLen: 0, hasNext: true },
      ], // tab
      tabCurrentIndex: 0, // 当前菜单下标
      tabCurrentType: -1, // 当前菜单类型
      optionUserId: 0, // 用户id
      loading: true,
      userBasicData: {}, // 基础数据
      courseTabList: [
        {
          name: '点播',
          type: 1,
        },
        {
          name: '直播',
          type: 2,
        },
        {
          name: '班级',
          type: 4,
        },
      ], // 课程tab
      courseType: 1, // 课程类型

      questionShow: false, // 提问窗口是否显示
      questionContent: '', // 提问输入内容
      keyboardheight: 0,
      attachImg: [],
      attachList: [],
    }
  },
  computed: {
    ...mapGetters({
      userInfo: 'user/getUserInfo',
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      globNavbarHeight: 'projectSetting/globNavbarHeight',
      globStatusBarHeight: 'projectSetting/globStatusBarHeight',
    }),
    lecturerHeaderHeightStyle() {
      return {
        height: this.globNavbarHeight + this.globStatusBarHeight + 'px',
      }
    },
    mescrollTop() {
      let tabHeight = uni.upx2px(80)
      let top =
        this.globNavbarHeight +
        this.globStatusBarHeight +
        uni.upx2px(140) +
        uni.upx2px(110) +
        tabHeight +
        'px'
      return top
    },
    // 当前用户是自己
    isUser() {
      return this.userBasicData.id == this.userInfo.id
    },
    // 当前用户是否是讲师
    isTeacher() {
      if (this.$u.test.empty(this.userBasicData)) return false
      return this.userBasicData.identity == 2
    },
    contentDisabled() {
      return this.$u.trim(this.questionContent).length == 0
    },
  },
  onLoad(option) {
    this.optionUserId = option.id
    this.getPersonData()
  },
  onBackPress({ from }) {
    if (from === 'navigateBack') {
      // #ifdef APP-PLUS
      this.$nextTick(() => {
        uniShare.hide()
      })
      return uniShare.isShow
      // #endif
      // #ifndef APP-PLUS
      return false
      // #endif
    }
    this.onBack()
    return true
  },
  onShareAppMessage() {
    let desc = ''
    if (this.userBasicData.identity == 2) {
      desc = this.delHtmlTag(this.userBasicData.info_text)
    } else {
      desc = this.userBasicData.signature
    }
    return {
      title: this.userBasicData.title || this.userBasicData.nick_name || '',
      desc: desc || '',
      path: '/pageFound/user/index?id=' + this.optionUserId,
      imageUrl: this.userBasicData.avatar_url,
    }
  },
  methods: {
    getPersonData() {
      this.loading = true
      this.$edu.api
        .getPersonHomeBase({
          user_id: this.optionUserId,
        })
        .then((res) => {
          const { data } = res
          this.userBasicData = data
          if (data.identity == 2) {
            this.tabCurrentType = 0
            this.tabList.unshift({ name: '介绍', type: 0 })
          } else {
            this.tabCurrentType = 1
          }
          setTimeout(() => {
            this.loading = false
            this.mescroll.resetUpScroll()
            // #ifdef H5
            // 公众号分享
            if (this.$edu.test.isWechat()) {
              let desc = ''
              let link = this.setting.appBaseUrl + '/pageFound/user/index?id=' + this.optionUserId
              if (this.userBasicData.identity == 2) {
                desc = this.delHtmlTag(this.userBasicData.info_text)
              } else {
                desc = this.userBasicData.signature
              }
              wxShare(
                {
                  title: this.userBasicData.title || this.userBasicData.nick_name || '',
                  desc: desc || '',
                  link: link,
                  imgUrl: this.userBasicData.avatar_url,
                },
                (res) => {
                  console.log(res)
                }
              )
            }
            // #endif
          }, 200)
        })
    },
    /*下拉刷新的回调 */
    downCallback() {
      this.mescroll.resetUpScroll()
    },
    /*上拉加载的回调 */
    async upCallback(page) {
      let data = null
      const type = this.tabCurrentType
      if (type == 0) {
        if (this.$u.test.empty(this.userBasicData.info_text)) {
          this.mescroll.endSuccess(0)
        } else {
          this.mescroll.endSuccess(1)
        }
      } else if (type == 1) {
        // 动态
        await this.$edu.api
          .getPersonHomeCircle({
            user_id: this.optionUserId,
            page: page.num,
            count: page.size,
          })
          .then((res) => {
            data = res.data.data
          })
      } else if (type == 2) {
        if (this.isTeacher) {
          await this.$edu.api
            .getTeacherCourse(this.userBasicData.id, {
              course_type: this.courseType,
              page: page.num,
              count: page.size,
            })
            .then((res) => {
              data = res.data.data
            })
        } else {
          await this.$edu.api
            .getHomeCourse({
              user_id: this.optionUserId,
              type: this.courseType,
              page: page.num,
              count: page.size,
            })
            .then((res) => {
              data = res.data.data
            })
        }
      }
      if (type != 0) {
        // 当前tab数据
        this.tabList.forEach((item) => {
          if (item.type == this.tabCurrentType) {
            if (page.num == 1) item.goods = [] //如果是第一页需手动制空列表
            item.goods = item.goods.concat(data) //追加新数据
            item.num = page.num // 页码
            item.curPageLen = data.length // 当前页长
            item.hasNext = this.mescroll.optUp.hasNext // 是否还有下一页
            this.mescroll.endSuccess(data.length)
          }
        })
      }
    },
    // 切换菜单
    tabChange(index) {
      // 当前菜单的数据
      let curTab = this.tabList[index]
      this.tabCurrentIndex = index
      this.tabCurrentType = curTab.type
      // 记录切换前滚动条的位置
      curTab.y = this.mescroll.getScrollTop()
      if (this.tabCurrentType == 0) {
        if (this.$u.test.empty(this.userBasicData.info_text)) {
          this.mescroll.resetUpScroll()
        } else {
          this.mescroll.endSuccess(1)
        }
        this.$nextTick(() => {
          this.mescroll.scrollTo(curTab.y, 0) // 恢复滚动条的位置
          this.mescroll.hideUpScroll()
        })
      } else {
        if (curTab.goods.length == 0) {
          // 没有初始化,则初始化
          this.mescroll.resetUpScroll()
        } else {
          // 初始化过,则恢复之前的列表数据
          this.mescroll.setPageNum(curTab.num + 1) // 恢复当前页码
          this.mescroll.endSuccess(curTab.curPageLen, curTab.hasNext) // 恢复是否有下一页或显示空布局
          this.$nextTick(() => {
            this.mescroll.scrollTo(curTab.y, 0) // 恢复滚动条的位置
          })
        }
      }
    },
    // 课程切换菜单
    courseTabChange(type) {
      if (this.courseType == type) return
      this.tabList.forEach((item) => {
        if (item.type == this.tabCurrentType) {
          item.goods = []
        }
      })
      this.courseType = type
      this.mescroll.resetUpScroll()
    },
    // 关注
    handleFollowChange() {
      // 是否登录
      this.$edu.judgeLogin(() => {
        const follow = this.isTeacher ? this.userBasicData.is_follow : this.userBasicData.followed
        const user_id = this.isTeacher ? this.userBasicData.user_id : this.userBasicData.id
        if (follow == 1) {
          this.$edu.api
            .getUserDelFollow({
              user_id: user_id,
            })
            .then((res) => {
              if (this.isTeacher) {
                this.userBasicData.is_follow = 0
              } else {
                this.userBasicData.followed = 0
              }
              this.$u.toast(res.msg)
            })
        } else {
          this.$edu.api
            .getUserFollow({
              user_id: user_id,
            })
            .then((res) => {
              if (this.isTeacher) {
                this.userBasicData.is_follow = 1
              } else {
                this.userBasicData.followed = 1
              }
              this.$u.toast(res.msg)
            })
        }
      })
    },
    // 打开提问
    openQuestion() {
      // 是否登录
      this.$edu.judgeLogin(() => {
        this.questionShow = true
      })
    },
    // 提交提问
    submitQuestion() {
      if (this.$u.trim(this.questionContent).length > 0) {
        const user_id = this.isTeacher ? this.userBasicData.user_id : this.userBasicData.id
        let query = {
          recive_user_id: user_id,
          content: this.$u.trim(this.questionContent),
        }
        if (this.attachList.length > 0) {
          query = {
            ...query,
            attach: String(this.attachList),
          }
        }
        this.$edu.api.getUserProblem(query).then((res) => {
          this.questionShow = false
          this.$u.toast(res.msg)
          this.questionContent = ''
          this.attachList = []
          this.attachImg = []
        })
      } else {
        this.$u.toast('提问内容不能为空')
      }
    },
    // 跳转
    toVisitor(url) {
      let id = 0
      if (this.isTeacher) {
        id = this.userBasicData.user_id
      } else {
        id = this.userBasicData.id
      }
      this.$u.route(url, {
        id: id,
      })
    },
    // 动态点赞
    handleDynamicLike(data) {
      this.$edu.api
        .postCircleLike({
          type: 1,
          obj_id: data.id,
          status: data.type,
        })
        .then((res) => {
          this.tabList.forEach((item) => {
            if (item.type == this.tabCurrentType) {
              item.goods.forEach((el) => {
                if (data.id == el.id) {
                  if (data.type == 1) {
                    el.is_like = 1
                    el.like_num++
                  } else {
                    el.is_like = 0
                    el.like_num--
                  }
                }
              })
            }
          })
        })
        .catch((err) => {
          this.$u.toast('操作频繁，请稍后重试')
        })
    },
    // 动态回复
    handleDynamicReply(id) {
      this.$u.route('/pageFound/circle/friendDetail', {
        circle_id: id,
      })
    },
    // 动态转发
    handleDynamicForward(id) {
      this.$u.route('/pageFound/circle/forwardCircle', id)
    },
    // 课程跳转
    handleCoursePath(id) {
      this.$u.route('pageCourse/course/details', {
        id: id,
      })
    },
    // 编辑资料
    toUserEdit() {
      this.$u.route('/pageUser/setting/userInfo')
    },
    // 跳转机构
    toScholl() {
      // #ifdef H5
      window.location.href = this.userBasicData.mhm_sdn
      // #endif
      // #ifndef H5
      this.$u.route('pageFound/school/home', {
        id: this.userBasicData.mhm_id,
      })
      // #endif
    },
    // 跳转动态
    toTopic(id) {
      this.$edu.route('/pageFound/topic/details', {
        id: id,
      })
    },
    questionFocus(e) {
      this.keyboardheight = e.detail.height
    },
    questionBlur() {
      this.keyboardheight = 0
    },
    questionInput(e) {
      this.questionContent = e.detail.value
    },
    onShare() {
      // #ifdef APP-PLUS
      let desc = ''
      if (this.userBasicData.identity == 2) {
        desc = this.delHtmlTag(this.userBasicData.info_text)
      } else {
        desc = this.userBasicData.signature
      }
      uniShare.show(
        {
          content: {
            //公共的分享参数配置  类型（type）、链接（herf）、标题（title）、summary（描述）、imageUrl（缩略图）
            type: 0,
            href: this.userBasicData.mhm_sdn + '/pageFound/user/index?id=' + this.optionUserId,
            title: this.userBasicData.title || this.userBasicData.nick_name || '',
            summary: desc || '',
            imageUrl: this.userBasicData.avatar_url,
          },
          menus: [
            {
              img: '/static/images/login_icon_wechat.png',
              text: '微信好友',
              share: {
                provider: 'weixin',
                scene: 'WXSceneSession',
              },
            },
            {
              img: '/static/images/login_icon_weibo.png',
              text: '微博',
              share: {
                provider: 'sinaweibo',
              },
            },
            {
              img: '/static/images/login_icon_qq.png',
              text: 'QQ',
              share: {
                provider: 'qq',
                type: 2,
              },
            },
          ],
          cancelText: '取消分享',
        },
        (e) => {}
      )
      // #endif
    },
    onListChange(lists) {
      this.attachImg = lists
    },
    deleteItem(index) {
      this.attachList.splice(index, 1)
      this.$refs.uUpload.remove(index)
    },
    // 去除富文本的标签
    delHtmlTag(html = '') {
      if (this.$u.test.empty(html)) return ''
      // 获取内容
      let reg = new RegExp('<.+?>|&nbsp;', 'g') //匹配html标签的正则表达式
      let text = html.replace(reg, '') //执行替换成空字符
      return text
    },
    // 返回上一页
    onBack() {
      let pages = getCurrentPages()
      let page = pages[pages.length - 2]
      if (this.$u.test.empty(page)) {
        this.$u.route({ type: 'switchTab', url: 'pages/index/index' })
      } else {
        this.$u.route({ type: 'back' })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.share-btn {
  margin-right: 30rpx;
}
.lecturer-wrap {
  background-color: #fff;
}
.lecturer-header-fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}
.lecturer-header {
  padding: 0 30rpx;
  @include bg-color();
  background-image: url('@/static/images/study_card_img.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  .lecturer-header__content {
    .avatar {
      margin-right: 20rpx;
    }
    .content {
      flex: 1;
    }
    .title {
      height: 40rpx;
      line-height: 40rpx;
      max-width: 240rpx;
      font-size: 32rpx;
      color: #ffffff;
      font-weight: bold;
      margin-right: 6rpx;
    }
    .desc {
      max-width: 240rpx;
      margin-top: 24rpx;
      font-size: 24rpx;
      color: #ffffff;
      line-height: 1;
      display: flex;
    }
    .follow-btn {
      background-color: white;
      border-radius: 4rpx;
      padding-left: 4rpx;
      padding-right: 10rpx;
      @include text-color();
      font-size: 22rpx;
      margin-right: 16rpx;
      height: 42rpx;
    }
    .question-btn {
      padding-left: 10rpx;
      padding-right: 10rpx;
      height: 42rpx;
      border: 2rpx solid #ffffff;
      border-radius: 4rpx;
      color: white;
      font-size: 22rpx;
      justify-content: center;
    }
  }

  .lecturer-header__visitor {
    height: 110rpx;
    align-items: center;
    justify-content: space-around;
    .num {
      text-align: center;
      font-size: 32rpx;
      font-weight: bold;
      color: white;
    }
    .text {
      margin-top: 6rpx;
      text-align: center;
      font-size: 24rpx;
      font-weight: 400;
      color: white;
    }
  }
}

.lecturer-tabs {
  height: 80rpx;
  background-color: #fff;
}

.lecturer-main {
  padding: 30rpx;
}

.lecturer-course-tab {
  .item {
    height: 55rpx;
    width: 130rpx;
    border-radius: 28rpx;
    background-color: #f7f7f7;
    margin-right: 30rpx;
    line-height: 55rpx;
    font-size: 28rpx;
    color: #606266;
    text-align: center;
    &.active {
      color: #ffffff;
      @include bg-color();
    }
  }
}

.question-wrap {
  padding: 20rpx 30rpx;
  .left {
    margin-left: 24rpx;
    margin-right: 24rpx;
    flex: 1;
    padding: 0 24rpx;
    background: #f7f7f7;
    border-radius: 28rpx;
    .textarea {
      width: 100%;
      padding: 20rpx 0;
      font-size: 26rpx;
      font-weight: 400;
      color: #303133;
    }
    ::v-deep .placeholder {
      font-size: 26rpx;
      font-weight: 400;
      color: #b7bac1;
    }
  }
  ::v-deep .edu-btn {
    width: 120rpx;
    padding: 0;
  }
  .pre-box {
    display: flex;
    flex-wrap: wrap;
    .pre-item {
      flex: 0 0 70rpx;
      height: 70rpx;
      position: relative;
      margin-top: 20rpx;
      margin-right: 32rpx;
    }
    .pre-item-image {
      width: 100%;
      height: 70rpx;
      border-radius: 8rpx;
    }
    .u-delete-icon {
      position: absolute;
      top: -8rpx;
      right: -8rpx;
      z-index: 10;
      background: rgba(48, 49, 51, 0.5);
      border-radius: 100rpx;
      width: 24rpx;
      height: 24rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
